package com.example.vault.controller;

import com.example.vault.entity.ConfigVo;
import com.example.vault.entity.Person;
import com.example.vault.entity.ResponseResultVo;
import lombok.Data;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.vault.core.VaultSysOperations;
import org.springframework.vault.core.VaultTemplate;
import org.springframework.vault.core.VaultTransitOperations;
import org.springframework.vault.support.VaultMount;
import org.springframework.vault.support.VaultResponse;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Data
@Log4j(topic = "秘钥处理类")
@RestController
public class VaultController {

    @Autowired
    private VaultTemplate vaultTemplate;

    //秘钥引擎路径
//    @Value("${vault_kv_path}")
    final String VAULT_KV_PATH = "kv/myapp";

    @RequestMapping(value = "/write2")
    public ResponseResultVo write2() {
        ResponseResultVo responseResultVo = new ResponseResultVo();
        try {
            Person person = new Person(1, "test001", "test001", "test001");
            vaultTemplate.write(VAULT_KV_PATH, person);
            responseResultVo.setResult(person, true, "保存秘钥成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存秘钥异常： " + e);
            responseResultVo.setResult(false, "404", "保存秘钥异常");
        }
        return responseResultVo;
    }

    @RequestMapping(value = "/write")
    public ResponseResultVo write(ConfigVo configVo) {
        ResponseResultVo responseResultVo = new ResponseResultVo();
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            configVo.setCreateTime(dateFormat.format(new Date()));
            vaultTemplate.write(configVo.getPath(), configVo);
            responseResultVo.setResult(configVo, true, "保存秘钥成功");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("保存秘钥异常： " + e);
            responseResultVo.setResult(false, "404", "保存秘钥异常");
        }
        return responseResultVo;
    }


    @RequestMapping(value = "/read")
    public ResponseResultVo read(@RequestParam(name = "path", defaultValue = VAULT_KV_PATH) String path) {

        ResponseResultVo responseResultVo = new ResponseResultVo();
        try {
            //查询secret/myapp目录下数据
//            VaultResponseSupport<Person> response = vaultTemplate.read(VAULT_KV_PATH, Person.class);
            VaultResponse response = vaultTemplate.read(path);
            Map<String, Object> data = response.getData();
            responseResultVo.setResult(data, true, "查询秘钥成功");
            System.out.println(response.getData());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询秘钥异常： " + e);
            responseResultVo.setResult(false, "404", "查询秘钥异常");
        }
        return responseResultVo;
    }

    @RequestMapping(value = "/delete")
    public ResponseResultVo delete(@RequestParam(name = "path", defaultValue = VAULT_KV_PATH) String path) {

        ResponseResultVo responseResultVo = new ResponseResultVo();
        try {
            //删除数据
            vaultTemplate.delete(path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("删除秘钥异常： " + e);
            responseResultVo.setResult(false, "404", "删除秘钥异常");
        }
        return responseResultVo;
    }

    @RequestMapping("/encryptOrDecrypt")
    public ResponseResultVo encryptOrDecrypt() {
        ResponseResultVo responseResultVo = new ResponseResultVo();
        try {
            //  Let's encrypt some data using the Transit backend.
            VaultTransitOperations transitOperations = vaultTemplate.opsForTransit();

            // We need to setup transit first (assuming you didn't set up it yet).
            VaultSysOperations sysOperations = vaultTemplate.opsForSys();

            if (!sysOperations.getMounts().containsKey("transit/")) {
                sysOperations.mount("transit", VaultMount.create("transit"));
                transitOperations.createKey("foo-key");
            }

            // Encrypt a plain-text value
            String ciphertext = transitOperations.encrypt("foo-key", "测试加密解密");
            System.out.println("Encrypted value");
            System.out.println("-------------------------------");
            System.out.println(ciphertext);
            System.out.println("-------------------------------");
            System.out.println();

            // Decrypt
            String plaintext = transitOperations.decrypt("foo-key", ciphertext);
            System.out.println("Decrypted value");
            System.out.println("-------------------------------");
            System.out.println(plaintext);
            System.out.println("-------------------------------");
            System.out.println();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("加密或者解密异常： " + e);
            responseResultVo.setResult(false, "404", "加密或者解密异常");
        }
        return responseResultVo;
    }

}
